<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="分类名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="商品类型名称"></el-input>
    </el-form-item>
    <el-form-item label="分类图片" prop="imgUrl">
<!--      <el-input v-model="dataForm.imgUrl" placeholder="图片URL"></el-input>-->
      <el-upload
        class="upload-demo"
        action="#"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :http-request="uploadImg"
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList">
        <img width="100px" height="100px" v-if="dataForm.imgUrl" :src="'http://localhost:8080/renren-fast' + dataForm.imgUrl"/>
        <br v-if="dataForm.imgUrl">
        <el-button size="small" type="primary">点击上传</el-button>
        <!--        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
      </el-upload>
    </el-form-item>
    <el-form-item label="样式描述" prop="cls">
      <el-input v-model="dataForm.cls" placeholder="样式"></el-input>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        type: 'category',
        fileList: [],
        visible: false,
        dataForm: {
          id: 0,
          name: '',
          imgUrl: '',
          cls: ''
        },
        dataRule: {
          name: [
            { required: true, message: '商品类型名称不能为空', trigger: 'blur' }
          ],
          imgUrl: [
            { required: true, message: '图片URL不能为空', trigger: 'blur' }
          ],
          cls: [
            { required: true, message: '样式不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.fileList = [];
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/manage/productcategory/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.productCategory.name
                this.dataForm.imgUrl = data.productCategory.imgUrl
                const parts = data.productCategory.imgUrl.split('/')
                this.fileList.push({
                  name: parts[parts.length - 1],
                  url: 'http://localhost:8080/renren-fast' + data.productCategory.imgUrl
                })
                this.dataForm.cls = data.productCategory.cls
              }
            })
          }
        })
      },
      uploadImg (item) {
        const fileObj = item.file
        console.log(fileObj.name)
        // FormData 对象
        const form01 = new FormData()
        // 文件对象
        form01.append('file', fileObj)
        this.$http({
          url: this.$http.adornUrl(`/manage/file/upload/${this.type}`),
          method: 'post',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          data: form01
        }).then(({data}) => {
          console.log(data)
          if (data && data.code === 0) {
            this.$message({
              message: '上传成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.fileList.push({
                  name: fileObj.name,
                  url: 'http://localhost:8080/renren-fast' + data.fileInfo
                })
                this.dataForm.imgUrl = data.fileInfo
              }
            })
          } else {
            this.$message({
              message: '上传失败',
              type: 'warning',
              duration: 1500,
              onClose: () => {
              }
            })
          }
        }).catch(() => {
          this.$message.error('异常错误')
        })
      },
      handleRemove (item, fileList) {
        console.log(item, fileList)
        var filename = item.name
        console.log('删除文件名：', filename)
        this.$http({
          url: this.$http.adornUrl(`/manage/file/delete/${this.type}`),
          method: 'post',
          data: this.$http.adornData({
            'filename': filename
          })
        }).then(({data}) => {
          console.log(data)
          if (data && data.code === 0) {
            this.$message({
              message: '移除成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.fileList = this.fileList.filter(item => item.name !== filename)
                this.dataForm.imgUrl = ''
              }
            })
          } else {
            this.$message({
              message: '移除失败',
              type: 'warning',
              duration: 1500,
              onClose: () => {
              }
            })
          }
        }).catch(() => {
          this.$message.error('异常错误')
        })
      },
      handlePreview (file) {
        console.log(file)
      },
      handleExceed (files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      beforeRemove (file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
      // 表单提交
      dataFormSubmit () {
        console.log(this.dataForm)
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/manage/productcategory/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'imgUrl': this.dataForm.imgUrl,
                'cls': this.dataForm.cls
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
